package models

import (
	"AQChain/common"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"time"
)

var (
	encodeTransferMissOwnerError  = errors.New("EncodeTransfer miss Owner")
	encodeTransferMissBuyerError  = errors.New("EncodeTransfer miss Buyer")
	encodeTransferMissFileIDError = errors.New("EncodeTransfer miss FileID")
)

// 记录交易
type Transfer struct {
	ID      string  `orm:"pk;column(id)" json:"id"`          // hash
	Owner   string  `orm:"column(owner)" json:"owner"`       // 拥有者
	Buyer   string  `orm:"column(buyer)" json:"buyer"`       // 购买者
	Price   float64 `orm:"column(price)" json:"price"`       // 价格
	FileID  string  `orm:"column(file_id)" json:"file_id"`   // 文件ID
	OwnerTx string  `orm:"column(owner_tx)" json:"owner_tx"` // 拥有者最后发送的Transaction.Hash
	BuyerTx string  `orm:"column(buyer_tx)" json:"buyer_tx"` // 购买者最后发送的Transaction.Hash
	Status  int32   `orm:"column(status)" json:"status"`
	// 0激活 1购买者交易申请中 2拥有者确认了交易 3购买者完成转账确认 4终止
	Timestamp string `orm:"column(timestamp)" json:"timestamp"` // 完成交易时间
}

// 对Creator CreateTime FileID 进行hash作为文件ID
func (t *Transfer) EncodeTransfer() string {
	h := sha256.New()
	h.Write([]byte(t.Owner))
	h.Write([]byte(t.Buyer))
	h.Write([]byte(t.FileID))
	sum := h.Sum(nil)
	return hex.EncodeToString(sum)
}

func TransferFromTx(tx *Transaction) *Transfer {
	tf := &Transfer{
		Price:  tx.Value,
		FileID: tx.FileID,
	}
	switch tx.Type {
	case 1:
		// 卖激活
		tf.Owner = tx.From
		tf.OwnerTx = tx.Hash
		tf.Status = 0
	case 2:
		// 买申请
		tf.Buyer = tx.From
		tf.Owner = tx.To
		tf.BuyerTx = tx.Hash
		tf.Status = 1
	case 3:
		// 卖拒绝
		tf.Buyer = tx.To
		tf.Owner = tx.From
		tf.OwnerTx = tx.Hash
		tf.Status = 0
	case 4:
		// 卖确认
		tf.Buyer = tx.To
		tf.Owner = tx.From
		tf.OwnerTx = tx.Hash
		tf.Status = 2
	case 5:
		// 买确认
		tf.Buyer = tx.From
		tf.Owner = tx.To
		tf.BuyerTx = tx.Hash
		tf.Timestamp = time.Now().Format(common.TimeFormat)
		tf.Status = 3
	case 6:
		// 买取消
		tf.Buyer = tx.From
		tf.Owner = tx.To
		tf.BuyerTx = tx.Hash
		tf.Status = 0
	case 7:
		// 卖终止
		tf.Owner = tx.From
		tf.Buyer = tx.To
		tf.OwnerTx = tx.Hash
		tf.Status = 4
	}

	tf.ID = tf.EncodeTransfer()
	return tf
}
